package com.bclz.leetcode

import java.util.StringJoiner


class ListNode[A]{
  var next:ListNode[A]=_
  var v:A=_


  def this(next:ListNode[A],v:A){
    this()
    this.v=v
    this.next=next
  }

  def this(v:A){
    this(null,v)
  }


  override def toString: String = {

    val joiner = new StringJoiner(",")
    var nextEle=this
    while(nextEle!=null){
      joiner.add(nextEle.v.toString)
      nextEle=nextEle.next
    }
    joiner.toString
  }

}

object Practise {


  def main(args: Array[String]): Unit = {
    val last = new ListNode[Int](5)
    val t = new ListNode(new ListNode[Int](new ListNode[Int](new ListNode[Int](new ListNode[Int](last, 4), 3), 2), 1),0)
//    val value = reverseNode(t)
  val value =  reverseNodeII(t,2,4)
    println(value)
  }

  def reverseNode[T](node:ListNode[T]):ListNode[T]={

    var last:ListNode[T]=null
    var next=node
    while(next!=null){
      last=new ListNode[T](last,next.v)
      next=next.next
    }
    last
  }

  def reverseNodeII[T](node:ListNode[T],m:Int,n:Int):ListNode[T] ={

    var nextNode=node
    var count=n-m+1
    var preCount=m
    var preNode:ListNode[T]=null
    while(preCount>0){


      if(preCount<=2){

        if(preCount==2){
          preNode=nextNode
          preCount-=1
          nextNode=nextNode.next
        }

        var last:ListNode[T]=null
        var startNode:ListNode[T]=null
        while(count>0){
          count-=1
          val isFirst=last==null
          last=new ListNode[T](last,nextNode.v)
          nextNode=nextNode.next
          if(isFirst){
            startNode=last
          }
          if(count==0){
            startNode.next=nextNode
            if(preNode!=null){
              preNode.next=last
              return node
            }else{
              return last
            }
          }
          preCount-=1
        }
      }

      preCount-=1
      nextNode=nextNode.next

    }
    node

  }

}
